package cn.com.nes.common.util;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

public class DBUitl {
	public static boolean isPicture(String pInput){
		
		String[] strs ={"bmp","png","jpg","jpeg","gif"};
		// 获得文件后缀名  
		String tmpName = pInput.substring(pInput.lastIndexOf(".") + 1,  
		                             pInput.length()); 
		
		for(int i=0; i<strs.length; i++){
			if(strs[i].equals(tmpName.toLowerCase()))
				return true;
		}
		
		return false;
	}
	
	public static String getDateMinute(String myDate, int offset) {
		java.text.SimpleDateFormat format = Globals.DATE_FORMAT_LONG ;
		java.util.Date beginDate;
		try {
			beginDate = format.parse(myDate);
			return  getDateMinute(beginDate, offset) ;
		} catch (ParseException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return null ;
	}
	
	public static String getImgSignURL(String objectName,int isys)  { 
		OSSClient ossClient = null ;
		String urlStr="" ;
		try {
			if(Globals.ISLOCALFILE){
				urlStr = "/nesctce/"+objectName ;
				return urlStr  ;
			}
			
			ossClient = new OSSClient(Globals.endpoint_ww, Globals.accessKeyId, Globals.accessKeySecret);
	    	Date expiration = new Date(new Date().getTime() + 5*60 * 1000);
	    	
	    	boolean found = ossClient.doesObjectExist(Globals.bucketName, objectName);
	    	if(!found){
	    		objectName = objectName.toLowerCase() ;
	    		found = ossClient.doesObjectExist(Globals.bucketName, objectName);
	    	}
	    	if(found){
	    		boolean isImage = isPicture(objectName);
	    		if(isImage){
	    			GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(Globals.bucketName, objectName, HttpMethod.GET);
		    		req.setExpiration(expiration);
		    		String style = "" ;
		    		 
		    		switch (isys) {
					case 0:
						break;
					case 1:
						style = "image/resize,m_lfit,w_110";
						break;
					case 2:
						style = "image/resize,m_lfit,w_510";
						break;
					}
		    		if(style!=null&&!style.equals("")){
		    			req.setProcess(style);
			    	}
		    		req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
		    		URL signedUrl = ossClient.generatePresignedUrl(req);
		    		urlStr = signedUrl.toString() ;
	    		}else{
	    			urlStr= "/"+Globals.WEBALIAS+"/images/nopreview.jpg" ;
	    		}
	    	}
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ossClient!=null) ossClient.shutdown() ; 
		}
		
		
		if(urlStr==null||urlStr.equals("")){
			urlStr= "/"+Globals.WEBALIAS+"/images/no.jpg" ;
		}
		return urlStr ;
    } 
	
	
	public static byte[] FiletoByteArray(String filename) throws IOException {  
		filename = Globals.IMG_PATH  + filename ;
        File f = new File(filename);  
        if (!f.exists()||!f.isFile()) {  
        	return null ;
        }  
  
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());  
        BufferedInputStream in = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(f));  
            int buf_size = 1024;  
            byte[] buffer = new byte[buf_size];  
            int len = 0;  
            while (-1 != (len = in.read(buffer, 0, buf_size))) {  
                bos.write(buffer, 0, len);  
            }  
            return bos.toByteArray();  
        } catch (IOException e) {  
            e.printStackTrace();  
            return null ;
        } finally {  
            try {  
                if(in!=null) in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            bos.close();  
        }  
    } 
	
	public static String convertString(String gbk) {
		String utf8 = "";
		try {
			utf8 = new String(gbk2utf8(gbk), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			utf8 = gbk;
		}
		return utf8;
	}
	
	private static String format(String value) {
		try {
			if (value == null || value.equals("")) {
				return value;
			}

			String[] source_stra = { "ALTER", "CALL", "CREATE", "DELETE",
					"GRANT", "INSERT", "LOAD", "LOCK", "MERGE", "MODIFY",
					"REMOVE", "RENAME", "REPLACE", "REVOKE", "SET", "SELECT",
					"START", "STOP", "USE", "UPDATE", "IMG", "HREF", "<SCRIPT",
					"OR", "TRUNCATE", "DROP" };

			String[] dest_stra = { "ＡLTER", "ＣALL", "ＣREATE", "ＤELETE",
					"ＧRANT", "ＩNSERT", "ＬOAD", "ＬOCK", "ＭERGE", "ＭODIFY",
					"ＲEMOVE", "ＲENAME", "ＲEPLACE", "ＲEVOKE", "ＳET", "ＳELECT",
					"ＳTART", "ＳTOP", "ＵSE", "ＵPDATE", "ＩMG", "HｒEF", "<ＳCRIPT",
					"OＲ", "TＲUNCATE", "DＲOP" };

			int idx = value.indexOf("\'");
			int idx_json = value.indexOf("{");
			if (idx >= 0 && idx_json < 0) {
				value = value.replaceAll("\'", "‘");
			}

			idx = value.indexOf("\"");
			if (idx >= 0 && idx_json < 0) {
				value = value.replaceAll("\"", "”");
			}

			for (int i = 0; i < source_stra.length; i++) {
				idx = value.toUpperCase().indexOf(source_stra[i]);
				if (idx >= 0) {
					idx = idx + source_stra[i].length();
					int len = value.length();
					if (len > idx) {
						char lastKey = value.charAt(idx);
						if (lastKey == '(' || lastKey == '#' || lastKey == ' '
								|| lastKey == '/') {
							value = value.replaceAll("(?i)" + source_stra[i],
									dest_stra[i]);
						}
					}

					if (source_stra[i].equals("<SCRIPT")) {
						value = value.replaceAll("(?i)" + source_stra[i],
								dest_stra[i]);
					}

				}
			}
		} catch (Exception e) {
		}
		return value;
	}
	
	public static String getReqParameter(HttpServletRequest request,String paramName) {
		String param = request.getParameter("paramName") ;
		param = format(param);
		return param ;
	}

	public static byte[] gbk2utf8(String chenese) {
		char c[] = chenese.toCharArray();
		byte[] fullByte = new byte[3 * c.length];
		for (int i = 0; i < c.length; i++) {
			int m = (int) c[i];
			String word = Integer.toBinaryString(m);

			StringBuffer sb = new StringBuffer();
			int len = 16 - word.length();
			for (int j = 0; j < len; j++) {
				sb.append("0");
			}
			sb.append(word);
			sb.insert(0, "1110");
			sb.insert(8, "10");
			sb.insert(16, "10");

			String s1 = sb.substring(0, 8);
			String s2 = sb.substring(8, 16);
			String s3 = sb.substring(16);

			byte b0 = Integer.valueOf(s1, 2).byteValue();
			byte b1 = Integer.valueOf(s2, 2).byteValue();
			byte b2 = Integer.valueOf(s3, 2).byteValue();
			byte[] bf = new byte[3];
			bf[0] = b0;
			fullByte[i * 3] = bf[0];
			bf[1] = b1;
			fullByte[i * 3 + 1] = bf[1];
			bf[2] = b2;
			fullByte[i * 3 + 2] = bf[2];

		}
		return fullByte;
	}

	public static String getDate(int offset) {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_SHORT;
		Date myDate = new Date();
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * offset;
		myDate.setTime(myTime * 1000);
		String mDate = formatter.format(myDate);
		return mDate;
	}
	//求选中日期的前一天
	public static String getSpecifiedDayBefore(String specifiedDay){
		if (specifiedDay == null || specifiedDay.equals("")) {
			specifiedDay = DBUitl.getDate(0);
		}
		Calendar c = Calendar.getInstance(); 
		Date date=null; 
		try { 
		date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay); 
		} catch (ParseException e) { 
		e.printStackTrace(); 
		} 
		c.setTime(date); 
		int day=c.get(Calendar.DATE); 
		c.set(Calendar.DATE,day-1); 

		String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 
		return dayBefore; 
	}
	//求选中日期的天数日期
	public static String getSpecifiedDay(String specifiedDay,int d){
		if (specifiedDay == null || specifiedDay.equals("")) {
			specifiedDay = DBUitl.getDate(0);
		}
		Calendar c = Calendar.getInstance(); 
		Date date=null; 
		try { 
		date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay); 
		} catch (ParseException e) { 
		e.printStackTrace(); 
		} 
		c.setTime(date); 
		int day=c.get(Calendar.DATE); 
		c.set(Calendar.DATE,day+d); 

		String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 
		return dayBefore; 
	}
	//求选中日期的前180天
	public static String getSpecifiedDayBefore_xny(String specifiedDay){
		if (specifiedDay == null || specifiedDay.equals("")) {
			specifiedDay = DBUitl.getDate(0);
		}
		Calendar c = Calendar.getInstance(); 
		Date date=null; 
		try { 
		date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay); 
		} catch (ParseException e) { 
		e.printStackTrace(); 
		} 
		c.setTime(date); 
		int day=c.get(Calendar.DATE); 
		c.set(Calendar.DATE,day-180); 
		String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 
		return dayBefore; 
	} 
	//求两个日期相差的天数
	public static int differentDaysByMillisecond(String date1,String date2) throws ParseException{
          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date3 = format.parse(date1);
            Date date4 = format.parse(date2);
            int days = (int) ((date4.getTime() - date3.getTime()) / (1000*3600*24));
	        return days;
	}

	public static Date StrToDate(String str) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	public static String getDate(Date myDate, int offset) {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_SHORT;
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * offset;
		myDate.setTime(myTime * 1000);
		String mDate = formatter.format(myDate);
		return mDate;
	}
	
	public static String getDateMinute(Date myDate, int offset) {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_LONG;
		long myTime = (myDate.getTime() / 1000) + 60 *  offset;
		myDate.setTime(myTime * 1000);
		String mDate = formatter.format(myDate);
		return mDate;
	}

	public static String getCurYear() {
		Calendar cal = new GregorianCalendar();
		int year = cal.get(Calendar.YEAR) ;
		int mon = cal.get(Calendar.MONTH)+1 ; 
		int date = cal.get(Calendar.DATE) ; 

        if((mon<3)||(mon==3)&&(date<=20)){
        	year = year - 1 ;
        }
        
		return String.valueOf(year);
	}

	public static int toHash(String key) {
		int arraySize = 11113; // 数组大小一般取质数
		int hashCode = 0;
		for (int i = 0; i < key.length(); i++) { // 从字符串的左边开始计算
			int letterValue = key.charAt(i) - 96;// 将获取到的字符串转换成数字，比如a的码值是97，则97-96=1
													// 就代表a的值，同理b=2；
			hashCode = ((hashCode << 5) + letterValue) % arraySize;// 防止编码溢出，对每步结果都进行取模运算
		}
		return hashCode;
	}


	public static boolean isNumber(String str) {
		if (str == null || str.equals("")) {
			return false;
		}
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后一位的数字的正则表达式
		java.util.regex.Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}

	public static long getDaySub(String beginDateStr, String endDateStr) {
		long day = 0;
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
				"yyyy-MM-dd");
		java.util.Date beginDate;
		java.util.Date endDate;
		try {
			beginDate = format.parse(beginDateStr);
			endDate = format.parse(endDateStr);
			day = (endDate.getTime() - beginDate.getTime())
					/ (24 * 60 * 60 * 1000);
			// System.out.println("相隔的天数="+day);
		} catch (ParseException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return day;
	}


	public static String getNullData(String data) {
		if (data == null || data.equals("") || data.equals("null")) {
			data = null;
		}
		return data;
	}

	public static String getNull(String data) {
		if (data == null || data.equals("null")) {
			data = "";
		}
		return data;
	}

	public static int isNumber1(String s) {

		String regex = "^[1-9][0-9]*\\.[0-9]+$|^[1-9][0-9]*$|^0+\\.[0-9]+$";
		char c = s.charAt(0);
		boolean bool;
		if (c == '+' | c == '-') {
			bool = s.substring(1).matches(regex);
		} else {
			bool = s.matches(regex);
		}
		if (bool) {
			return 1;
		} else {
			return 0;
		}
	}
	
	public static boolean isDigit(String str) {
		Boolean strResult = false ;
		try {
			Double.valueOf(str) ;
			strResult = true ;
		} catch (Exception e) {
		}
		return strResult ;
	}	

	public static String removeZero(String data) {
		if (!isNumber(data)) {
			return data;
		}
		float tmp = Float.parseFloat(data);
		data = String.valueOf(tmp);
		return data;
	}


	public static StringBuffer sql_check(StringBuffer sql) {
		String sqlstr = sql.toString();
		String[] inj_stra = { "update ", "delete ", "exec ", "master",
				"truncate ", "declare ", ";" };
		for (int i = 0; i < inj_stra.length; i++) {
			if (sqlstr.toLowerCase().indexOf(inj_stra[i]) >= 0) {
				sqlstr = sqlstr.replaceAll("(?i)" + inj_stra[i], "");
			}
		}
		StringBuffer sb = new StringBuffer(sqlstr);
		return sb;
	}
	public static StringBuffer sql_check_jc(StringBuffer sql) {
		String sqlstr = sql.toString();
		String[] inj_stra = { "update ", "delete ", "exec ", "master",
				"truncate ", "declare " };
		for (int i = 0; i < inj_stra.length; i++) {
			if (sqlstr.toLowerCase().indexOf(inj_stra[i]) >= 0) {
				sqlstr = sqlstr.replaceAll("(?i)" + inj_stra[i], "");
			}
		}
		StringBuffer sb = new StringBuffer(sqlstr);
		return sb;
	}

	// 判断文件夹是否存在
	public static boolean DirIsExists(String dir) {
		File file_dir = new File(dir);
		try {
			if (file_dir.exists()) {
				return true;
			} else {
				file_dir.mkdirs();
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	
	//在本地保存图片
	public static boolean SaveImageToLocal(InputStream inputStream,
			String filename) {
		DataOutputStream outputStream = null;
		try {
			filename = Globals.IMG_PATH + filename;
			String path=filename.substring(0,filename.lastIndexOf('/'));
			if (inputStream == null)
				return false;
			File file = new File(path) ;
			if(!file.exists()){
				file.mkdirs() ;
			}
			outputStream = new DataOutputStream(new FileOutputStream(filename));
			int len = inputStream.available() ;
			System.out.println(len);
			int byteCount = 0;
			byte[] bytes = new byte[1024 * 1024];
			while ((byteCount = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, byteCount);
			}
			outputStream.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if(outputStream!=null) outputStream.close();
			} catch (IOException e) {
				return false;
			}
			try {
				if(inputStream!=null) inputStream.close();
			} catch (IOException e) {
				return false;
			}
		}
	}
	
	
	public static boolean SaveImageFromStream(InputStream inputStream,
			String filename) {
		OSSClient ossClient = null ;
		try {
			if(Globals.ISLOCALFILE){
				return SaveImageToLocal(inputStream,filename) ;
			}
			ossClient = new OSSClient(Globals.endpoint, Globals.accessKeyId, Globals.accessKeySecret);
			ossClient.putObject(Globals.bucketName, filename, inputStream) ;
			filename = Globals.IMG_PATH + filename;
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if(ossClient!=null) ossClient.shutdown();
		}
	}
	
	public static String getSysParam(Connection conn,String csm,String xzqhdm) throws SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String res=null ;
		try {
			if(xzqhdm.length()>6){
				xzqhdm = xzqhdm.substring(0,6) ;
			}
			sb.append("select csz from t_xtcs where csm='").append(csm).append("' and xzqhdm like '").append(xzqhdm).append("%'") ;
			sb = DBUitl.sql_check(sb);
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = ps.executeQuery();
			if (rs.next()) {
				res = rs.getString("csz") ;
			}
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
		}
		return res;
	}
	
	public static Connection getDBConnect_JDBC() {
		Connection conn = null;
		 String url =
		 "jdbc:mysql://rm-2ze3340731300n995no.mysql.rds.aliyuncs.com:3306/ctceyun?characterEncoding=utf-8";
		 String user = "ctceyun";
		 String password = "NESctce2017";
		 try {
		// //Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
		 Class.forName("com.mysql.jdbc.Driver").newInstance();
		 } catch (InstantiationException e) {
		 e.printStackTrace();
		 } catch (IllegalAccessException e) {
		 e.printStackTrace();
		 } catch (ClassNotFoundException e) {
		 e.printStackTrace();
		 }
		 try {
		 conn = DriverManager.getConnection(url, user, password);
		 conn.setAutoCommit(false);
		 } catch (SQLException e1) {
		 e1.printStackTrace();
		 }
		return conn;
	}
	
	public static String getPlanQUeryStr(String xzqhdm) {
		String str="  and (a.byc3 is null or a.byc3 ='')  " ;
		
		if(xzqhdm!=null&&xzqhdm.length()>6){
			xzqhdm = xzqhdm.substring(0,6) ;
			str="  and (a.byc3 is null or a.byc3 =''  or a.byc3 like '"+xzqhdm+"%')   " ;
		}
		return str ;
	}
	
	
	public static String getQueryXzqh(int jb,String xzqhdm)
	{
		String result="";
		
		if(xzqhdm.equals("86"))
			result= ""; //86全国，没有限制条件
		else if(jb==0)
			result= ""; //86全国，没有限制条件
		else if(jb==1)
			result= xzqhdm.substring(0, 2) ;
		else if(jb==2)
			result= xzqhdm.substring(0, 4);
		else if(jb==3)
			result = xzqhdm.substring(0,6);
		else if(jb==4)
			result = xzqhdm.substring(0,9);
		else if(jb==5)
			result = xzqhdm;
		else if(jb==6)
			result = xzqhdm;
		else
			result = xzqhdm;
		return result;
	}
	
	public static String getQueryXzqhDown(int jb,String xzqhdm)
	{
		String result="";
//		if(jb>=4&&xzqhdm.endsWith("000")){
//			result = xzqhdm.length()>=6? xzqhdm.substring(0,6):xzqhdm;
//			return result;
//		}
		if(xzqhdm.equals("86"))
			result= "";
		else if(jb==0)
			result= "";
		else if(jb==1)
			result= xzqhdm.length()>=2? xzqhdm.substring(0, 2):xzqhdm;
		else if(jb==2)
			result=  xzqhdm.length()>=4? xzqhdm.substring(0, 4):xzqhdm;
		else if(jb==3)
			result =  xzqhdm.length()>=6? xzqhdm.substring(0,6):xzqhdm;
		else if(jb==4){
			result = xzqhdm.length()>=9? xzqhdm.substring(0,9):xzqhdm;
		}
		else if(jb==5)
			result = xzqhdm.length()>=12? xzqhdm.substring(0,12):xzqhdm;
		else if(jb==6)
			result =  xzqhdm.length()>=15? xzqhdm.substring(0,15):xzqhdm;
		else
			result = xzqhdm;
		return result;
	}
	
	
	
	
	public static int getDataType(String input) {   
		input = input== null?"":input ;
		int result = 0 ;
		if (!input.matches("^[-\\+]?[0-9]+([.]{0,1}[0-9]+){0,1}$")){
			result = 1 ;   
	    }else if (input.matches("^[-\\+]?[0-9]+$")){
	    	result = 2 ; 
	    	//手机号会出现转换异常 ，所以添加 shihx
			try{
				Integer.parseInt(input);
			}catch(Exception e){
				result=1;
			}
	    }else {
	    	result = 3 ; 
	    } 
		return result ;
    } 
	
	
	public static String getCacheData(Connection conn,String key) throws SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String res=null ;
		try {
			
			sb.append("select v from t_cache where k=?") ;
			sb = DBUitl.sql_check(sb);
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			ps.setString(1, key);
			rs = ps.executeQuery();
			if (rs.next()) {
				res = rs.getString("v") ;
			}
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
		}
		return res;
	}
	
	public static boolean setCacheData(Connection conn,String key,String val) throws SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement ps = null;
		ResultSet rs = null;
		boolean res=false ;
		try {
			sb.append("delete from t_cache where k = ? ");
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			ps.setString(1, key);
			ps.executeUpdate();
			ps.close();
			
			sb.delete(0, sb.length()) ;
			sb.append("insert into t_cache (k,v) values(?,?)");
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			ps.setString(1,key);
			ps.setString(2, val);
			ps.executeUpdate();
			res=true ;
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
		}
		return res;
	}	
	
	
	public static void writeToFile(InputStream is,String fileName) throws IOException{
	    BufferedInputStream in=null;
	    BufferedOutputStream out=null;
	    in=new BufferedInputStream(is);
	    out=new BufferedOutputStream(new FileOutputStream(fileName));
	    int len=-1;
	    byte[] b=new byte[1024];
	    while((len=in.read(b))!=-1){
	        out.write(b,0,len);
	    }
	    in.close();
	    out.close();
	}

	// 除法运算默认精度  
    private static final int DEF_DIV_SCALE = 10;  
  
    /** 
     * 精确加法 
     */  
    public static double add(double value1, double value2) {  
        BigDecimal b1 = BigDecimal.valueOf(value1);  
        BigDecimal b2 = BigDecimal.valueOf(value2);  
        return b1.add(b2).doubleValue();  
    }  
  
    /** 
     * 精确减法 
     */  
    public static double sub(double value1, double value2) {  
        BigDecimal b1 = BigDecimal.valueOf(value1);  
        BigDecimal b2 = BigDecimal.valueOf(value2);  
        return b1.subtract(b2).doubleValue();  
    }  
  
    /** 
     * 精确乘法 
     */  
    public static double mul(double value1, double value2) {  
        BigDecimal b1 = BigDecimal.valueOf(value1);  
        BigDecimal b2 = BigDecimal.valueOf(value2);  
        return b1.multiply(b2).doubleValue();  
    }  
  
    /** 
     * 精确除法 使用默认精度 
     */  
    public static double div(double value1, double value2) throws IllegalAccessException {  
        return div(value1, value2, DEF_DIV_SCALE);  
    }  
  
    /** 
     * 精确除法 
     * @param scale 精度 
     */  
    public static double div(double value1, double value2, int scale) throws IllegalAccessException {  
        if(scale < 0) {  
            throw new IllegalAccessException("精确度不能小于0");  
        }  
        BigDecimal b1 = BigDecimal.valueOf(value1);  
        BigDecimal b2 = BigDecimal.valueOf(value2);  
        // return b1.divide(b2, scale).doubleValue();  
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();  
    }  
  
    /** 
     * 四舍五入 
     * @param scale 小数点后保留几位 
     */  
    public static double round(double v, int scale) throws IllegalAccessException {  
        return div(v, 1, scale);  
    }  
      
    /** 
     * 比较大小 
     */  
    public static boolean equalTo(BigDecimal b1, BigDecimal b2) {  
        if(b1 == null || b2 == null) {  
            return false;  
        }  
        return 0 == b1.compareTo(b2);  
    }  
    
    //根据SB_ID得到表名
    public static String getHisTableName(String sb_id)  { 
    	StringBuffer result = new StringBuffer() ;
    	if(sb_id==null||sb_id.equals("")){
    		return " t_sbyxqk_his " ;
    	}
    	String b = String.format("%04d", Math.abs(sb_id.hashCode()) % 500);
		result.append(" t_sbyxqk_his_").append(b).append(" ") ;
        return result.toString() ; 
    }  
    
	
	public static String getZBRQ(Connection conn,String zbnf,String azrq,String xzqhdm) throws SQLException{
		String zbrq="";
		int rq=Integer.parseInt(azrq.substring(5,7).concat(azrq.substring(8,10)));
		int aznf0=Integer.parseInt(azrq.substring(0,4));
		String QNJJSSJ=getQNJJSSJ(conn,xzqhdm);
		int QNJJSSJ0=Integer.parseInt(QNJJSSJ.substring(0,2).concat(QNJJSSJ.substring(3,5)));
		if(zbnf.contains(".5")){
			int zbnf0=Integer.parseInt(zbnf.substring(0,1));
			String QNJJSSJ_BN=getQNJJSSJ_BN(conn,xzqhdm);
			if(rq<QNJJSSJ0){
				zbrq=String.valueOf(aznf0+zbnf0-1).concat("-".concat(QNJJSSJ_BN).concat(" 23:59:59"));
			}else{
				zbrq=String.valueOf(aznf0+zbnf0).concat("-".concat(QNJJSSJ_BN).concat(" 23:59:59"));
			}
		}else{
			int zbnf0=Integer.parseInt(zbnf);
			if(rq<QNJJSSJ0){
				zbrq=String.valueOf(aznf0+zbnf0-1).concat("-".concat(QNJJSSJ).concat(" 23:59:59"));
			}else{
				zbrq=String.valueOf(aznf0+zbnf0).concat("-".concat(QNJJSSJ).concat(" 23:59:59"));
			}
		}
		//System.out.println(zbrq);
		return zbrq;
	}
	public static String getQNJJSSJ(Connection conn,String xzqhdm) throws SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String res=null ;
		try {
			xzqhdm = xzqhdm.substring(0,4) ;
			sb.append("select csz from t_xtcs where xzqhdm = '").append(xzqhdm).append("' and csm='ZBRQEND' ") ;
			sb = DBUitl.sql_check(sb);
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = ps.executeQuery();
			if (rs.next()) {
				res = rs.getString("csz") ;
			}
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
		}
		return res;
	}
	public static String getQNJJSSJ_BN(Connection conn,String xzqhdm) throws SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String res=null ;
		try {
			xzqhdm = xzqhdm.substring(0,4) ;
			sb.append("select csz from t_xtcs where xzqhdm = '").append(xzqhdm).append("' and csm='ZBRQEND_BN' ") ;
			sb = DBUitl.sql_check(sb);
			ps = conn.prepareStatement(sb.toString(),
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = ps.executeQuery();
			if (rs.next()) {
				res = rs.getString("csz") ;
			}
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
		}
		return res;
	}
	
	public static void downloadFile(HttpServletRequest request,
			HttpServletResponse response,String filepath,String fileName) throws Exception{
		ServletOutputStream sos = null;
		InputStream inStream = null;
		OSSClient ossClient = null;
		try{
			// 下载本地文件
			File file = new File(Globals.IMG_PATH + filepath);
			if (file.exists()) {
				// 读到流中
				inStream = new FileInputStream(Globals.IMG_PATH + filepath);// 文件的存放路径
				// 设置输出的格式
				response.reset();
				response.setContentType("bin");
				response.addHeader(
						"Content-Disposition",
						"attachment; fileName="
								+ URLEncoder.encode(fileName, "UTF-8"));
				// 循环取出流中的数据
				byte[] b = new byte[100];
				int len;
				while ((len = inStream.read(b)) > 0)
					response.getOutputStream().write(b, 0, len);
				// inStream.close();
			} else {
				ossClient = new OSSClient(Globals.endpoint,
						Globals.accessKeyId, Globals.accessKeySecret);
				OSSObject ossObject = ossClient.getObject(
						Globals.bucketName, filepath);
				InputStream inputStream = ossObject.getObjectContent();
				// 设置输出的格式
				response.reset();
				response.setContentType("bin");
				response.addHeader(
						"Content-Disposition",
						"attachment; fileName="
								+ URLEncoder.encode(fileName, "UTF-8"));
				OutputStream outStream = response.getOutputStream(); // 得到向客户端输出二进制数据的对象

				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = inputStream.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				inputStream.close();
				outStream.flush();
				outStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
			if (sos != null) {
				sos.close();
			}
			if (inStream != null) {
				inStream.close();
			}
		}
	}

	public static Connection getDBConn_newmall() {
		Connection conn = null;
		try {
			Context initCtx = new InitialContext();
			DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/shopmall");

			initCtx.close();
			if (ds != null) {
				try {
					conn = ds.getConnection();
					// System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date())+ "  crmeb 当前连接数=" + ds.getNumActive());
					conn.setAutoCommit(false);
					// System.err.println("JNDI 获取成功!");
				} catch (SQLException e) {
					e.printStackTrace();
					System.err.println("JNDI 获取失败!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("JNDI 获取失败!");
		}
		return conn;
	}

	public static void main(String[] args) {
//		System.out.println("61880709299900791272".hashCode());
//		String b = String.format("%04d", Math.abs("61880709299900791272".hashCode()) % 500);
//		System.out.println(b);
//		sendAppNotice("1d3cbea41c664c8493d35708b55820b0","通知","123");
	}

	public static String getImgvVideoSignURL(String objectName, int isys) {
		OSSClient ossClient = null;
		String urlStr = "";
		try {
			ossClient = new OSSClient(Globals.endpoint_ww, Globals.accessKeyId, Globals.accessKeySecret);
			Date expiration = new Date(new Date().getTime() + 15 * 60 * 1000);

			boolean found = ossClient.doesObjectExist(Globals.bucketName, objectName);
			if (found) {
				boolean isImage = isPicture(objectName);
				if (isImage) {
					GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(Globals.bucketName, objectName,
							HttpMethod.GET);
					req.setExpiration(expiration);
					String style = "";
					switch (isys) {
						case 0:
							break;
						case 1:
							style = "image/resize,m_lfit,w_110";
							break;
						case 2:
							style = "image/resize,m_lfit,w_510";
							break;
						case 3:
							style = "image/resize,m_lfit,w_510";
							break;
					}
					if (style != null && !style.equals("")) {
						req.setProcess(style);
					}
					req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
					URL signedUrl = ossClient.generatePresignedUrl(req);
					urlStr = signedUrl.toString();
				} else {
					boolean isVideo = isVideo(objectName);
					if (isVideo) {
						GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(Globals.bucketName,
								objectName, HttpMethod.GET);
						req.setExpiration(expiration);
						String style = "";
						switch (isys) {
							case 0:
								break;
							case 1:
								style = "video/snapshot,t_10000,m_fast";
								break;
							case 2:
								style = "video/snapshot,t_10000,m_fast";
								break;
							case 3:
								style = "video/snapshot,t_10000,m_fast";
								break;
						}
						if (style != null && !style.equals("")) {
							req.setProcess(style);
						}
						req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
						URL signedUrl = ossClient.generatePresignedUrl(req);
						urlStr = signedUrl.toString();
					} else {
						boolean isAudio = isAudio(objectName);
						if (isAudio) {
							GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(Globals.bucketName,
									objectName, HttpMethod.GET);
							req.setExpiration(expiration);
							req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
							URL signedUrl = ossClient.generatePresignedUrl(req);
							urlStr = signedUrl.toString();
						} else {
							urlStr = "/" + Globals.WEBALIAS + "/images/nopreview.jpg";
						}
					}
				}
			}

		} catch (Exception e) {
		} finally {
			if (ossClient != null)
				ossClient.shutdown();
		}

		if (urlStr == null || urlStr.equals("")) {
			urlStr = "/" + Globals.WEBALIAS + "/images/no.jpg";
		}
		return urlStr;
	}

	public static boolean isAudio(String pInput) {

		String[] strs = { "mp3"};
		// 获得文件后缀名
		String tmpName = pInput.substring(pInput.lastIndexOf(".") + 1, pInput.length());

		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equals(tmpName.toLowerCase()))
				return true;
		}

		return false;
	}

	public static boolean isVideo(String pInput) {

		String[] strs = { "mp4", "avi", "mov", "wmv", "rmvb", "mkv", "m4v" };
		// 获得文件后缀名
		String tmpName = pInput.substring(pInput.lastIndexOf(".") + 1, pInput.length());

		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equals(tmpName.toLowerCase()))
				return true;
		}

		return false;
	}

	/**
	 * 手动分页
	 * @param list
	 * @param pageIndex
	 * @param pageSize
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> paginate(List<T> list, int pageIndex, int pageSize) {
		int startIndex = (pageIndex-1) * pageSize;
		int endIndex = Math.min(startIndex + pageSize, list.size());
		// 如果开始索引大于列表长度，返回一个空列表
		if (startIndex > list.size()) {
			return new ArrayList<>();
		}
		// 使用 subList 方法获取当前页的数据
		return list.subList(startIndex, endIndex);
	}
}